package com.huaixia.cozeapi.clint;


import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class CozeApiClient {
    private static final String API_URL = "https://api.coze.cn/open_api/v2/chat";
    private final OkHttpClient httpClient;

    public CozeApiClient() {
        this.httpClient = new OkHttpClient();
    }

    public String sendChatMessage(String personalAccessToken, String botId, String conversationId, String userId, String query, Boolean stream) {
        // 创建请求体
        String jsonBody = String.format("{\"conversation_id\": \"%s\", \"bot_id\": \"%s\", \"user\": \"%s\", \"query\": \"%s\", \"stream\": %b}",
                conversationId, botId, userId, query, stream);

        RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json"));

        // 创建请求
        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + personalAccessToken)
                .addHeader("Content-Type", "application/json")
                        .addHeader("Accept", "text/event-stream")
                        .post(body)
                        .build();

        if (!stream) {
            // 发送HTTP请求并获取响应
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    return response.body().string();
                } else {
                    throw new IOException("Request failed with status code: " + response.code() + ", Response: " + response.body().string());
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            // 使用SSE处理流式请求
            CountDownLatch latch = new CountDownLatch(1);
            StringBuilder result = new StringBuilder();
            try {
                // 处理SSE请求
                httpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        latch.countDown();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful() && response.body() != null) {
                            BufferedReader reader = new BufferedReader(response.body().charStream());
                            String line;
                            while ((line = reader.readLine()) != null) {
                                if (line.startsWith("data:")) {
                                    result.append(line.substring(5).trim()).append("\n");
                                    System.out.println("Receiving: " + line.substring(5).trim());
                                }
                            }
                        } else {
                            System.err.println("SSE request failed with status code: " + response.code());
                        }
                        latch.countDown();
                    }
                });

                // 等待所有消息接收完毕
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


            return result.toString();
        }
    }
}
